﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace ICommonLibrary.Security {

    public class Cipher {

        private readonly SymmetricAlgorithm _algorithm;
        private readonly byte[] _key;
        private readonly byte[] _iv;

        public Cipher(SymmetricAlgorithm alg, byte[] key, byte[] iv) {
            _algorithm = alg;
            _key = key;
            _iv = iv;
        }

        public string EncryptToBase64(string data) {
            return Convert.ToBase64String(Crypt(_algorithm.CreateEncryptor(_key, _iv), Encoding.UTF8.GetBytes(data)));
        }

        public string DecryptFromBase64(string data) {
            return Encoding.UTF8.GetString(Crypt(_algorithm.CreateDecryptor(_key, _iv), Convert.FromBase64String(data)));
        }

        private static byte[] Crypt(ICryptoTransform cryptor, byte[] data) {
            var m = new MemoryStream(data.Length * 2);
            using (Stream c = new CryptoStream(m, cryptor, CryptoStreamMode.Write)) {
                c.Write(data, 0, data.Length);
            }
            return m.ToArray();
        }
    }
}